package com.gebiafu.service.impl;

import com.gebiafu.exception.DaoException;
import com.gebiafu.mapper.UserMapper;
import com.gebiafu.pojo.User;
import com.gebiafu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * title: UserServiceImpl
 * author: Gebiafu
 * date: 2021/07/02 11:03
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired//密码加密工具
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserMapper userMapper;
    @Value("${sys.default.authorities}")
    private String defaultAuthorities;
    @Override
    @Transactional(rollbackFor = {DaoException.class})
    public int addUser(User user,String repeatPassword) {
        try {
            //校验请求参数中的两次密码是否一致
            if(repeatPassword==null || !repeatPassword.equals(user.getPassword())){
                //两次密码不一致,或者有参数错误
                throw new DaoException("注册用户数据错误");
            }
            //加密用户输入的密码
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            //提供默认的权限
            if(user.getAuthorities()==null){
                user.setAuthorities(defaultAuthorities);
            }
            //保存用户到数据库
            int i = userMapper.insertUser(user);
            //判断新增数据结果
            if(i!=1){
            //新增数据到数据库发生错误
                throw new DaoException("用户注册错误");
            }
            return i;
        } catch (DaoException e) {
            //代码中通过判断逻辑抛出的异常,直接传递给控制器
            throw e;
        }catch (Exception e){
            //mybatis抛出异常,处理后封装成自定义异常传递给控制器
            throw new DaoException("用户注册错误",e);
        }
    }

    @Override
    public User findUser(String username) {
        try {
            return userMapper.selectUser(username);
        } catch (Exception e) {
            throw new DaoException("用户登陆错误",e);
        }
    }
}
